﻿using LD.BC;
using LD.Host;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using 右下角弹窗.DiagShow;

namespace LD.Tool
{
    public partial class ToolIfFrm : FrmToolBase
    {
        public ToolIfFrm()
        {
            InitializeComponent();
            this.Shown += ToolMoveFrm_Shown;
            this.btn_ok.Click += Btn_ok_Click;
        }

        private void Btn_ok_Click(object sender, EventArgs e)
        {
            Dialog dialog = new Dialog();

            List<ToolIfParam> ifParams = new List<ToolIfParam>();
            foreach (DataGridViewRow item in this.dgv_data.Rows)
            {
                if (item.Cells["判定类型"].Value?.ToString() == "全局变量")
                {
                    if (item.Cells["全局变量"].Value != null &&
                    item.Cells["判定符"].Value != null &&
                    item.Cells["判定值"].Value != null &&
                    item.Cells["运行流程"].Value != null)
                    {
                        string variable = item.Cells["全局变量"].Value.ToString();
                        //数据类型判定
                        var cacheVar = Cache.Var.Where(p => p.Name == variable).FirstOrDefault();
                        DataType dataType = (DataType)Enum.Parse(typeof(DataType), cacheVar.DataType);
                        switch (dataType)
                        {
                            case DataType.Int:
                                if (!int.TryParse(item.Cells["判定值"].Value.ToString(), out var v1))
                                {
                                    dialog.Warning("数据类型错误");
                                    return;
                                }
                                break;
                            case DataType.Float:
                                if (!float.TryParse(item.Cells["判定值"].Value.ToString(), out var v2))
                                {
                                    dialog.Warning("数据类型错误");
                                    return;
                                }
                                break;
                            case DataType.Bool:
                                if (!bool.TryParse(item.Cells["判定值"].Value.ToString(), out var v3))
                                {
                                    dialog.Warning("数据类型错误");
                                    return;
                                }
                                break;
                            case DataType.Double:
                                if (!double.TryParse(item.Cells["判定值"].Value.ToString(), out var v4))
                                {
                                    dialog.Warning("数据类型错误");
                                    return;
                                }
                                break;
                            default:
                                break;
                        }

                        ifParams.Add(new ToolIfParam()
                        {
                            ToolIfMode = (ToolIfMode)Enum.Parse(typeof(ToolIfMode), item.Cells["判定类型"].Value.ToString()),
                            Variable = variable,
                            OpChar = (OpChar)Enum.Parse(typeof(OpChar), item.Cells["判定符"].Value.ToString()),
                            OpVar = item.Cells["判定值"].Value.ToString(),
                            FlowName = item.Cells["运行流程"].Value.ToString(),
                            IsWaitOver = Convert.ToBoolean(item.Cells["等待结束"].Value)
                        });
                    }
                }
                else if (item.Cells["判定类型"].Value?.ToString() == "IO")
                {
                    if (item.Cells["IO类型"].Value != null && item.Cells["IO点位"].Value != null && item.Cells["IO有效值"].Value != null && item.Cells["运行流程"].Value != null)
                    {
                        ifParams.Add(new ToolIfParam()
                        {
                            ToolIfMode = (ToolIfMode)Enum.Parse(typeof(ToolIfMode), item.Cells["判定类型"].Value.ToString()),
                            IoType = (IoType)Enum.Parse(typeof(IoType), item.Cells["IO类型"].Value.ToString()),
                            IoName = item.Cells["IO点位"].Value.ToString(),
                            LowHig = (LevelType)Enum.Parse(typeof(LevelType), item.Cells["IO有效值"].Value.ToString()),
                            FlowName = item.Cells["运行流程"].Value.ToString(),
                            IsWaitOver = Convert.ToBoolean(item.Cells["等待结束"].Value ?? true)
                        });
                    }
                }
                else
                {
                    dialog.Warning("请选择判定类型");
                    return;
                }
            }
            this.TB_Tool.Param = JsonConvert.SerializeObject(ifParams);
        }

        private void ToolMoveFrm_Shown(object sender, EventArgs e)
        {
            Init();
        }
        private void Init()
        {
            this.判定类型.DataSource = EnumHelper.GetEnumDescription<ToolIfMode>();
            this.判定类型.DisplayMember = "Name";
            this.判定类型.ValueMember = "Name";

            this.IO类型.DataSource = EnumHelper.GetEnumDescription<IoType>();
            this.IO类型.DisplayMember = "Name";
            this.IO类型.ValueMember = "Name";

            this.IO有效值.DataSource = EnumHelper.GetEnumDescription<LevelType>();
            this.IO有效值.DisplayMember = "Name";
            this.IO有效值.ValueMember = "Name";

            this.全局变量.DataSource = Cache.Var;
            this.全局变量.DisplayMember = "Name";
            this.全局变量.ValueMember = "Name";

            this.判定符.DataSource = EnumHelper.GetEnumDescription<OpChar>();
            this.判定符.DisplayMember = "Name";
            this.判定符.ValueMember = "Name";

            var flowList = Appbus.PartNo.Config.Flow.Where(p => p.FlowType == (int)FlowType.流程).ToList();
            this.运行流程.DataSource = flowList;
            this.运行流程.DisplayMember = "Name";
            this.运行流程.ValueMember = "Name";

            if (this.TB_Tool.Param == null)
                return;
            var ioList = JsonConvert.DeserializeObject<List<ToolIfParam>>(this.TB_Tool.Param);
            foreach (var item in ioList)
            {
                int index = this.dgv_data.Rows.Add();

                DataGridViewComboBoxCell cobCellName = this.dgv_data["判定类型", index] as DataGridViewComboBoxCell;
                cobCellName.Value = item.ToolIfMode.ToString();
                toolIfMode_Change(index, item.ToolIfMode);

                cobCellName = this.dgv_data["IO类型", index] as DataGridViewComboBoxCell;
                cobCellName.Value = item.IoType?.ToString();
                if (item.IoType != null)
                    ioList_Get(index, (IoType)item.IoType);

                cobCellName = this.dgv_data["IO点位", index] as DataGridViewComboBoxCell;
                cobCellName.Value = item.IoName;
                cobCellName = this.dgv_data["IO有效值", index] as DataGridViewComboBoxCell;
                cobCellName.Value = item.LowHig?.ToString();

                this.dgv_data["判定值", index].Value = item.OpVar;
                this.dgv_data["等待结束", index].Value = item.IsWaitOver;

                DataGridViewComboBoxCell cobCellName0 = this.dgv_data["全局变量", index] as DataGridViewComboBoxCell;
                cobCellName0.Value = item.Variable;

                DataGridViewComboBoxCell cobCellName1 = this.dgv_data["判定符", index] as DataGridViewComboBoxCell;
                cobCellName1.Value = item.OpChar.ToString();

                DataGridViewComboBoxCell cobCellName2 = this.dgv_data["运行流程", index] as DataGridViewComboBoxCell;
                cobCellName2.Value = item.FlowName;
            }
        }
        private void tsb_new_Click(object sender, EventArgs e)
        {
            this.dgv_data.Rows.Add();
        }

        private void dgv_data_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            string value = this.dgv_data[e.ColumnIndex, e.RowIndex].Value?.ToString();
            if (!string.IsNullOrEmpty(value) && dgv_data.Columns[e.ColumnIndex].HeaderText == "判定类型")
                toolIfMode_Change(e.RowIndex, (ToolIfMode)Enum.Parse(typeof(ToolIfMode), value));
            if (!string.IsNullOrEmpty(value) && dgv_data.Columns[e.ColumnIndex].HeaderText == "IO类型")
            {
                ioList_Get(e.RowIndex, (IoType)Enum.Parse(typeof(IoType), value));
            }
        }

        private void ioList_Get(int row, IoType value)
        {
            ((DataGridViewComboBoxCell)dgv_data.Rows[row].Cells[2]).Items.Clear();
            dgv_data.Rows[row].Cells[2].Value = "";

            var io = BcFactory.Instance.Config.IoList.Where(p => p.IoType == (value == IoType.输入 ? 0 : 1)).ToList();
            foreach (var item in io)
            {
                ((DataGridViewComboBoxCell)dgv_data.Rows[row].Cells[2]).Items.Add(item.Name);
            }
        }

        private void tsb_sub_Click(object sender, EventArgs e)
        {
            if (this.dgv_data.SelectedRows.Count > 0)
            {
                var rows = this.dgv_data.SelectedRows;
                foreach (DataGridViewRow item in rows)
                {
                    this.dgv_data.Rows.Remove(item);
                }
            }
        }

        private void toolIfMode_Change(int row, ToolIfMode mode)
        {
            if (mode == ToolIfMode.全局变量)
            {
                setCellStyle(row, 1, false);
                setCellStyle(row, 2, false);
                setCellStyle(row, 3, false);
                setCellStyle(row, 4, true);
                setCellStyle(row, 5, true);
                setCellStyle(row, 6, true);
            }
            else if (mode == ToolIfMode.IO)
            {
                setCellStyle(row, 1, true);
                setCellStyle(row, 2, true);
                setCellStyle(row, 3, true);
                setCellStyle(row, 4, false);
                setCellStyle(row, 5, false);
                setCellStyle(row, 6, false);
            }
        }

        private void setCellStyle(int row, int column, bool enable)
        {
            dgv_data.Rows[row].Cells[column].ReadOnly = !enable;

            //DataGridViewComboBoxCell cobCellName = this.dgv_data[row, column] as DataGridViewComboBoxCell;
            ////var control = ((DataGridViewComboBoxCell)dgv_data.Rows[row].Cells[column]);
            //cobCellName.DisplayStyle = enable ? DataGridViewComboBoxDisplayStyle.ComboBox : DataGridViewComboBoxDisplayStyle.DropDownButton;

            if (!enable)
                dgv_data.Rows[row].Cells[column].Value = "";
        }
    }
}
